package cn.airfei.aircore.core.utils;

import cn.airfei.aircore.core.storage.Pojo.FileUtilPojo;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author air
 * @create 2018-09-23 下午4:27
 */
@Data
public class FileUtil {
    private String relativePath = "";       // 相对路径
    private String absolutePath = "";       // 绝对路径
    private String oldName = "";            // 原文件名
    private String newName = "";            // 新文件名


    /**
     * @param file 文件
     * @param path 文件存放路径
     * @return
     */
    public boolean upload(MultipartFile file, String path) {
        LocalDate toDay = LocalDate.now();

        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 重新命名文件
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        String relativePath = toDay + "/" + newFileName + suffixName;      // 相对路径
        String realPath = path + relativePath;

        File dest = new File(realPath);
        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            //保存文件
            file.transferTo(dest);
            setOldName(fileName);
            setNewName(newFileName + suffixName);
            setRelativePath(relativePath);
            setAbsolutePath(realPath);
            return true;
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
        return false;
    }


    /**
     * 读取文件夹及子文件夹下所有文件
     *
     * @param path
     * @return
     */
    public List<FileUtilPojo> readAllFiles(String path) {
        List<FileUtilPojo> fileUtilPojoList = new ArrayList<>();
        File file = new File(path);
        recursionReadFiles(file, fileUtilPojoList);
        return fileUtilPojoList;
    }


    /**
     * 递归读取
     *
     * @param file
     * @param fileUtilPojoList
     */
    private static void recursionReadFiles(File file, List<FileUtilPojo> fileUtilPojoList) {
        File[] fs = file.listFiles();
        for (File f : fs) {
            if (f.isDirectory())    //若是目录，则递归
                recursionReadFiles(f, fileUtilPojoList);
            if (f.isFile()) {
                FileUtilPojo fileUtilPojo = new FileUtilPojo();
                fileUtilPojo.setFilePath(f.getAbsolutePath());
                fileUtilPojo.setModifiedTime(LocalDateTime.ofInstant(Instant.ofEpochMilli(f.lastModified()), ZoneId.systemDefault()));
                fileUtilPojoList.add(fileUtilPojo);
            }
        }
    }


}


